package com.ebor.utils.config.filter;

import com.ebor.utils.config.RequestBodyWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * RequestBody增强过滤器
 * @author C
 */
@WebFilter(filterName = "requestBodyFilter",urlPatterns = {"/*"})
@Order(Integer.MIN_VALUE)
@Slf4j
public class RequestBodyFilter implements Filter {


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        //requestWrapper中保存着供二次使用的请求数据
        if(StringUtils.equalsIgnoreCase(HttpMethod.POST.name(), ((HttpServletRequest) request).getMethod()) &&
                StringUtils.equalsIgnoreCase("application/json", request.getContentType())) {
            ServletRequest requestWrapper = new RequestBodyWrapper((HttpServletRequest) request);
            chain.doFilter(requestWrapper, response);
        } else {
            chain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {
    }

}